package membertask

import (
	"context"
	"strconv"
	"strings"

	"mall/common/cachex"
	"mall/common/globalkey"
	"mall/service/backend/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/setting/rpc/settingclient"
)

type (
	// MemberTask is an interface to be customized, add more methods here,
	// and implement the added methods in customMemberTask.
	MemberTask interface {
		List() ([]*types.MemberTaskInfo, error)
	}

	customMemberTask struct {
		ctx    context.Context
		svcCtx *svc.ServiceContext
	}
)

func NewMemberTask(ctx context.Context, svcCtx *svc.ServiceContext) MemberTask {
	return &customMemberTask{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *customMemberTask) List() (resp []*types.MemberTaskInfo, err error) {
	memberTaskKey := cachex.LocalMemberTask

	localCacheMemberTaskList, ok := l.svcCtx.LocalCache.Get(memberTaskKey)
	if ok {
		resp = localCacheMemberTaskList.([]*types.MemberTaskInfo)
	} else {
		resp, err = l.list()
		if err != nil {
			return nil, err
		}

		l.svcCtx.LocalCache.Set(memberTaskKey, resp)
	}

	return resp, nil
}

func (l *customMemberTask) list() (resp []*types.MemberTaskInfo, err error) {
	var preload string = "memberTask:Id,Name,Slug,Desc,PicId,PicUrl,Gems"
	var filters []string
	filters = append(filters, "Status,equalTo:" + strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	res, err := l.svcCtx.SettingRpc.GetMemberTaskList(l.ctx, &settingclient.BaseListReq{
		Preload:    &preload,
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     pointy.GetPointer("Sort:0"),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			resp = append(resp, &types.MemberTaskInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: v.Id,
				},
				Name:        v.Name,
				Slug:        v.Slug,
				Description: v.Description,
				PicId:       v.PicId,
				PicUrl:      v.PicUrl,
				Gems:        v.Gems,
			})
		}
	}

	return resp, nil
}
